package examples.rrc;

import java.io.*;
import java.net.*;

public class Checker extends Thread {
    public final static int DEFAULT_INPUT_PORT = 8041;
    protected int port;
    protected ServerSocket listen_socket;

    public static void fail(Exception e, String msg) {
	System.err.println(msg + ":" + e);
	System.exit(1);
    }

    public Checker(int port) {
	if(port == 0) port = DEFAULT_INPUT_PORT;
	this.port = port;
	try {	
		listen_socket = new ServerSocket(port);
	}
	catch(IOException e) {fail(e,"Exception creating Checker socket");}
	System.out.println("Checker:listening on port " + port);
	this.start();
    }

    public void run() {
	try {
	    while(true) {
		    Socket client_socket = listen_socket.accept();
		    Connection2ER c = new Connection2ER(client_socket);
	    }
	}
	catch(IOException e) {
	    fail(e, "Exception while listening for Connection2ERs");
	}
    }
    public static void main(String[] args)
    {
	int port = 0;
	if(args.length == 1) {
	    try {
		    port = Integer.parseInt(args[0]);
	    }
	    catch(NumberFormatException e){port = 0;}
	    new Checker(port);
	} else new Checker(port);
    }
}

class Connection2ER extends Thread {
    protected Socket client;
    protected DataInputStream in;

    boolean IC ;
    boolean GD ;

    public Connection2ER(Socket client_socket) {
	client = client_socket;
	IC = false;
	GD = false;
	try {
	    in = new DataInputStream(client.getInputStream());
	}
	catch(IOException e) {
	    try{client.close();} catch(IOException e2){}
	    System.err.println(
		    "Exception while getting socket streams: " +e);
		return;
	}
	this.start();
    }

    public void run() {
	try {
	    while(true) {
		if( in.readLine().equals("startGD")) {
		    GD = true;
		} else if (in.readLine().equals("endGD")) {
		    GD = false;
		} else if (in.readLine().equals("startIC")) {
		    IC = true;
		    if( !GD) {
			violation();
		    }
		} else if (in.readLine().equals("endIC")) {
		    IC = false;
		}
	    }
	}
	catch(EOFException e){}
	catch(IOException e){System.err.println(e);}
	finally{ try {client.close();} catch(IOException e2){}}
    }
    public static void violation() {
	System.err.println( 
	    "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
	System.err.println( 
	    "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
	System.err.println( 
	    "-=-=-=-=  VIOLATION of safeRRC property !!!!! =-=-=-=-=-");
	System.err.println( 
	    "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
	System.err.println( 
	    "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
    }
    
}
